<?php

namespace Users\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class UserManagerController extends AbstractActionController
{

    public function indexAction()
    {
        $this->layout('layout/myaccount');
        $userTable = $this->getServiceLocator()->get('Users\Model\UserTable');
        $users = $userTable->fetchAll();
        return new ViewModel(array(
            'users' => $users
        ));
    }
    
    public function editAction()
    {
        $userTable = $this->getServiceLocator()->get('Users\Model\UserTable');
        $user = $userTable->getUser($this->params()->fromRoute('id'));
        $form = $this->getServiceLocator()->get('UserEditForm');
        
        $form->bind($user);
        
        $request = $this->getRequest();
        
        if($request->isPost())
        {
            $form->setData($request->getPost());
            if($form->isValid())
            {
                $userTable = $this->getServiceLocator()->get('Users\Model\UserTable');
                $userTable->saveUser($user);
                return $this->redirect()->toRoute('users/user-manager');
            }
        }
        
        $viewModel = new ViewModel(array(
            'form' => $form , 
            'user_id' => $this->params()->fromRoute('id')
        ));
        return $viewModel;
    }
    
    public function deleteAction()
    {
        $userTable = $this->getServiceLocator()->get('Users\Model\UserTable');
        $userTable->deleteUser($this->params()->fromRoute('id'));
        return $this->redirect()->toRoute('users/user-manager');
    }

}

